package mk

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"new_for_deepseek_rabbitmq/config"
)

const (
	ARTICLE_URL = "/content-service/cnt_article"
)

// ArticleRequest 文章发布请求结构体
type MkArticleRequest struct {
	Title               string   `json:"title"`
	Content             string   `json:"content"`
	KeywordIndex        string   `json:"keyword_index"`
	PageDescribe        string   `json:"page_describe"`
	AuthorNickName      string   `json:"authorNickName"`
	CoverImg            string   `json:"coverImg"`
	Categories          []string `json:"categories"`
	RecommendList       []string `json:"recommendList"`
	VisibleRange        int      `json:"visibleRange"`
	WechatSubscribe     int      `json:"wechatSubscribe"`
	RecommendUserRegist int      `json:"recommendUserRegist"`
	Fields              []string `json:"fields"`
	Industries          []string `json:"industries"`
	Labels              []string `json:"labels"`
	OpenForTenant       bool     `json:"openForTenant"`
	Status              string   `json:"status"`
	Files               []string `json:"files"`
	LinkUrl             string   `json:"linkUrl"`
	Type                string   `json:"type"`
	PageStatus          bool     `json:"page_status"`
	PageHeadline        string   `json:"page_headline"`
}

type MkArticleResponse struct {
	Code string `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		Id string `json:"id"`
	} `json:"data"`
}

// PublishArticle 发布文章方法
func (m *Mk) PublishArticle(article MkArticleRequest) (mkId string, err error) {
	// 登录
	token, err := m.Login()
	if err != nil {
		return
	}

	// 发布文章参数
	jsonData, err := json.Marshal(article)
	if err != nil {
		return
	}

	// 发布文章请求
	req, err := http.NewRequest("POST", config.DefaultConfig.Mk.Url+ARTICLE_URL, bytes.NewBuffer(jsonData))
	if err != nil {
		return
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("token", token)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}

	// 解析响应体
	var result MkArticleResponse
	if err = json.Unmarshal(body, &result); err != nil {
		return
	}

	// 判断发布文章是否成功
	if result.Code != "0" {
		err = fmt.Errorf("发布文章失败: %v", string(body))
		return
	}

	return result.Data.Id, nil
}
